<template>
  <div style="width: 100%; height: 100%">

    <vxe-grid ref="tableRef" v-bind="gridOptions">
      <template #toolbar_buttons>
        <Button type="primary" @click="handleCreate">新增</Button>
        <ImpExcel @success="excelSuccessFn" dateFormat="YYYY-MM-DD">
          <Button class="m-3" :loading="loading"> 导入名单Excel </Button>
        </ImpExcel>

        <ImpExcel @success="excelSuccessFn2" dateFormat="YYYY-MM-DD">
          <Button class="m-3" :loading="loading"> 导入专业经验 </Button>
        </ImpExcel>
        <Button type="primary" @click="syncOfficeUserFn" :loading="loading">更新后勤人员钉钉信息</Button>
        <ImpExcel @success="excelSuccessFn3" dateFormat="YYYY-MM-DD">
          <a-button class="m-3" :loading="loading"> 导入历史业绩Excel </a-button>
        </ImpExcel>

        <a-button @click="aoaToExcel"> 下载历史业绩模版 </a-button>
      </template>
      <template #action="{ row }">
        <TableAction outside :actions="[
          {
              label:'修改',
              onClick: handleEdit.bind(null, row),
          },
           {
              label:'删除',
              color: 'error',
              loading: row.loading,
              popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',

                  confirm: handleDelete.bind(null, row),
                },
             },
        ]
        " />
      </template>

    </vxe-grid>
    <FormModal @register="register" @success="handleSuccess" />

    <Modal v-model:visible="applyViewShow" title="导入信息有误" @ok="applyViewClose">
      <div>
        <p v-for="(item, index) in msgList">{{ item }} </p>
      </div>
    </Modal>
  </div>
</template>
<script lang="ts" setup>
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';

import { BasicTable, useTable, TableAction } from '@/components/Table';
import { officeUserList, deleteOfficeUser,importOfficeUser,importWorkYear,syncOfficeUser,importUserSatisfaction } from '@/api/sys/sysData';
import { useDrawer } from '@/components/Drawer';

import {onMounted, reactive, ref} from 'vue';

import FormModal from './FormModal.vue';

import { columns, searchFormSchema,vxeTableColumns,vxeTableFormSchema } from './role.data';
import { useMessage } from "@/hooks/web/useMessage";
import {Button, Modal} from 'ant-design-vue';
import { useGo } from "@/hooks/web/usePage";
import {aoaToSheetXlsx, ImpExcel} from "@/components/Excel";
import {importGood} from "@/api/sys/shop";

const go = useGo();

defineOptions({ name: 'ywDeptList' });
const { createMessage } = useMessage();

// const [register, { openModal, closeModal }] = useModal();
const [register, { openDrawer,closeDrawer }] = useDrawer();

const loading=ref(false);
const msgList = ref([]);
const applyViewShow = ref(false);

const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },
  exportConfig:{},
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
    },
  },
});

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field + 'Like'] = value;
    });
  }
  // console.log("----json:", json);
  // ywApproveList xftList
  return officeUserList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}


function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
  });
}

onMounted(() => {
  // dd.ready(function() {
  //
  // }
})


function handleEdit(record: Recordable) {
  record.isUpdate=true;
  openDrawer(true, record);

}



function handleDelete(record: Recordable) {
  //console.log(record);
  record.loading=true;
  deleteOfficeUser(record).then(res => {
    createMessage.success(res.message);
    handleSuccess();
  })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
      record.loading=false;
    });
}

function handleSuccess() {
  tableRef.value.commitProxy('query');

}


function applyViewOpen() {
  applyViewShow.value = true;
}

function applyViewClose() {
  applyViewShow.value = false;
}


function syncOfficeUserFn(){
  loading.value = true;
  syncOfficeUser(null).then(res=>{
    if(res.code === 200){
      tableRef.value.commitProxy('reload');

    }else{
      createMessage.error(res.message);
    }
  }).finally(()=>{
    loading.value = false;
    })
}


/**
 * 导入excel
 *
 */
const arrHeader = [
  {
    key: 'userName',
    value: '姓名',
  },
  {
    key: 'gender',
    value: '性别',
  },
  {
    key: 'addTimeStr',
    value: '入厂日期',
  },
  {
    key:'manageYear',
    value: '管理经验参考年限'
  },
  {
    key:'specialtyYear',
    value: '专业经验参考年限'
  },
  {
    key:'education',
    value: '学历'
  },
  {
    key:'specialty',
    value: '专业'
  }
];

function changeSubmitArr(results) {
  let data = {
    list: [],
  };
  // let list = [];
  results.forEach((r) => {
    let json = {};
    for (let key in r) {
      arrHeader.forEach((e) => {
        if (e.value == key) {
          json[e.key] = r[key];
        }
      });
    }
    data.list.push(json);
  });
  return data;
}

function excelSuccessFn(list) {
  let results = list[0].results;
  // console.log(results);
  //去除第一行文字提示 shift 删除第一行
  // results.shift();
  let data = changeSubmitArr(results);
  // console.log(data);
  // return;
  loading.value = true;
  importOfficeUser(data)
    .then((res) => {
      loading.value = false;

      if (res.code == 200) {
        if (res.data && res.data.length > 0) {

          msgList.value = res.data;
          applyViewOpen();
        } else {
          createMessage.success('导入成功!');
          tableRef.value.commitProxy('reload');
        }
      } else {
        loading.value = false;

        createMessage.error(res.message);
      }
    })
    .catch((err) => {
      loading.value = false;
    });
}


/**
 * 导入专业经验
 *
 */
const arrHeader2 = [
  {
    key: 'userName',
    value: '姓名',
  },
  {
    key: 'type',
    value: '人员类型',
  },
  {
    key: 'postRequestName',
    value: '担任岗位',
  },
  {
    key:'birthdate',
    value: '出生日期'
  },
  {
    key:'addTime',
    value: '入司日期'
  },
  {
    key:'firstWordTime',
    value: '工作统计时间节点'
  },
  {
    key:'workYear',
    value: '参考工作经验'
  },

  {
    key:'firstManageTime',
    value: '管理统计时间节点'
  },
  {
    key:'manageYear',
    value: '管理经验参考年限'
  },

  {
    key:'firstPostTime',
    value: '岗位统计时间节点'
  },
  {
    key:'specialtyYear',
    value: '专业经验参考年限'
  },
  {
    key:'workYearLog',
    value: '工作经验年限'
  },

  {
    key:'workYearLog',
    value: '管理经验年限'
  },

  {
    key:'specialtyYearLog',
    value: '岗位专业经验年限'
  },

  {
    key:'specialty',
    value: '专业'
  },
  {
    key:'specialtyMatching',
    value: '专业相符'
  },
  {
    key:'education',
    value: '学历'
  },
  {
    key:'remark',
    value: '备注'
  },
];

function changeSubmitArr2(results) {
  let data = {
    list: [],
  };
  // let list = [];

  results.forEach((r) => {
    let json = {};
    for (let key in r) {
      arrHeader2.forEach((e) => {
        if (e.value == key) {

          /**
           *           addTime
           *           firstWordTime
           *           firstManageTime
           *           firstPostTime
           */

          if(r[key]||r[key]==0){
            if(key=='出生日期'||key=='入司日期'||key=='工作统计时间节点'||key=='管理统计时间节点'||key=='岗位统计时间节点'){
              if(r[key]){
                json[e.key] = r[key]+" 00:00:00";
              }
            }else {
              json[e.key] = r[key];

            }

          }

        }
      });
    }
    data.list.push(json);
  });
  return data;
}

function excelSuccessFn2(list) {
  let results = list[0].results;
  // console.log(results);
  //去除第一行文字提示 shift 删除第一行
  // results.shift();
  let data = changeSubmitArr2(results);
  // console.log(data);
  // return;
  loading.value = true;
  importWorkYear(data)
    .then((res) => {
      loading.value = false;

      if (res.code == 200) {
        if (res.data && res.data.length > 0) {

          msgList.value = res.data;
          applyViewOpen();
        } else {
          createMessage.success('导入成功!');
          tableRef.value.commitProxy('reload');
        }
      } else {
        loading.value = false;

        createMessage.error(res.message);
      }
    })
    .catch((err) => {
      loading.value = false;
    });
}



/**
 * 导入 历史业绩
 */
const arrHeader3=[
  {
    key:"userName",
    value:"姓名"
  },
  {
    key:"year",
    value:"年份"
  },
  {
    key:"level",
    value:"满意度"
  },
  {
    key:"note",
    value:"明细"
  },
];


function changeSubmitArr3(results){
  let data={
    list:[]
  }
  let list=[];
  // console.log("---arrHeader::",arrHeader)
  // console.log("---results:",results)
  results.forEach(r=>{
    let json={};
    for(let key in r){
      arrHeader3.forEach(e=>{
        if(e.value==key){
          json[e.key]=r[key];
        }
      })
    }
    data.list.push(json)
  });
  return data;
}

function excelSuccessFn3(list){
  let results=list[0].results;
  // console.log(results);
  let data=changeSubmitArr3(results);
  //  console.log(data)
  loading.value=true;
  importUserSatisfaction(data.list).then(res=>{

    if (res.code == 200) {
      if (res.data && res.data.length > 0) {

        msgList.value = res.data;
        applyViewOpen();
      } else {
        createMessage.success('导入成功!');
        tableRef.value.commitProxy('reload');
      }
    } else {
      loading.value = false;

      createMessage.error(res.message);
    }

  }).finally(()=>{
    loading.value=false;
  })
}
function aoaToExcel() {
  // 保证data顺序与header一致
  let arrHeader=[ "姓名","年份","满意度","明细","说明:'满意度'必须填写为:不太满意、基本满意、满意、很满意 的其中一种;年份:2025;"];
  aoaToSheetXlsx({
    data: [],
    header: arrHeader,
    filename: '历史业绩导入模版.xlsx',
  });
}





</script>
